package niumao.minecraft.uhc.commands;

import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.io.File;

public class Travel implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender commandSender, Command cmd, String label, String[] args) {
        if (commandSender instanceof Player) {
            Player sender = (Player) commandSender;
            if (!sender.isOp()) {
                sender.sendMessage("Only Op can execute this command!");
                return true;
            }
            if (cmd.getName().equalsIgnoreCase("travel")) {
                if (args.length == 1) {
                    String name = args[0];

                    if (name.equalsIgnoreCase("logs") || name.equalsIgnoreCase("plugins") || name.equalsIgnoreCase("backup")) {
                        sender.sendMessage("cannot find this world!");
                        return true;
                    }

                    File file = new File(name);
                    if (!(file.exists() && file.isDirectory())) {
                        sender.sendMessage("cannot find this world!");
                        return true;
                    }

                    WorldCreator worldCreator = new WorldCreator(name);
                    World world = Bukkit.createWorld(worldCreator);
                    assert world != null;
                    if (name.equalsIgnoreCase(sender.getWorld().getName())) {
                        sender.sendMessage("You are already in this world");
                        return true;
                    }
                    sender.teleport(world.getSpawnLocation());
                    return true;
                }
                return false;
            }
        }
        commandSender.sendMessage(ChatColor.RED + "only Player can executor this command!");
        return true;
    }
}
